import CONFIG from '../config'
//import { getUser } from 'auth'
import axios from 'axios'
import { hashHistory } from 'react-router';

axios.interceptors.response.use(response =>response , (err) => {
  if (err && err.response) {
    debugger;
    switch (err.response.status) {
      case 400: err.message = '请求错误(400)' ; break;
      case 401: err.message = '未授权，请重新登录(401)'; setTimeout(() => { hashHistory.push('/login') }, 1000); break;
      case 403: err.message = '拒绝访问(403)'; break;
      case 404: err.message = '请求出错(404)'; break;
      case 408: err.message = '请求超时(408)'; break;
      case 500: err.message = '服务器错误(500)'; break;
      case 501: err.message = '服务未实现(501)'; break;
      case 502: err.message = '网络错误(502)'; break;
      case 503: err.message = '服务不可用(503)'; break;
      case 504: err.message = '网络超时(504)'; break;
      case 505: err.message = 'HTTP版本不受支持(505)'; break;
      default: err.message = `连接出错(${err.response.status})!`;
    }
  }else{
    err.message = '连接服务器失败!'
  }
  // Feedback.toast.error(err.message);
  return Promise.reject(err);
});

axios.defaults.timeout = 10000
axios.defaults.headers.post['Content-Type'] = 'application/x-www=form-urlencoded'

export default {
  async fetchGet (url, params={}) {
    let data = await axios.get(CONFIG.SERVICE_HOST + url, { params : params, headers : fetchHeader() })
    return after(data)
  },
  async fetchQuickSearch (url) {
    let data = await axios.get(CONFIG.SERVICE_HOST + url , { headers : fetchHeader() })
    return after(data)
  },
  async fetchPost (url, params = {}) {
    let data = await axios.post(CONFIG.SERVICE_HOST + url, params , { headers : fetchHeader() })
    return after(data)
  }
}

// export const fetchHeader = () => {
//   let user = getUser()
//   if(!user.logined){ return null }
//   return { Authorization :'Bearer ' + user.accessToken, role : user.role, user : user.user  }
// }

export const after = (data) => {
  if(data.state < 200 || data.state >= 400){ throw { message : data.statusText } }
  if(!data.data.success){ throw { message : data.data.error } }
  return data.data.result
}
